import threading
from typing import Tuple
from queue import Queue
import socket


class MySocketServer(threading.Thread):

	def __init__(self, address: Tuple[str, int], in_queue: Queue, out_queue: Queue):
		super().__init__()
		self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.__socket.bind(address)
		self.__socket.listen(2)
		self.__inData = in_queue
		self.__outData = out_queue

	def __waitClient(self):
		print("等待客户端连接")
		c_socket, c_addr = self.__socket.accept()
		print(f"接收到客户端连接:{c_addr}")
		return c_socket, c_addr

	def sendData(self, c_socket, raw, c_addr):
		c_socket.send(raw)
		res = c_socket.recv(1024).decode()
		print(f"{c_socket}->{res}")
		if res == 'T':
			self.__outData.put(res)

	def run(self) -> None:
		esp8266_1, addr1 = self.__waitClient()
		esp8266_2, addr2 = self.__waitClient()
		while True:
			raw = self.__inData.get().encode()
			print(f"sendData->{raw}")
			self.sendData(esp8266_1, raw, addr1)
			self.sendData(esp8266_2, raw, addr2)


serverInQueue = Queue(5)
serverOutQueue = Queue(5)
server = MySocketServer(('0.0.0.0', 8778), serverInQueue, serverOutQueue)
